package com.estronger.shopmanage.ui.order.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.estronger.shopmanage.R;
import com.estronger.shopmanage.base.BaseActivity;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.BeanImage;
import com.estronger.shopmanage.bean.StringBean;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.ui.order.adapter.AddImagesAdapter;
import com.estronger.shopmanage.ui.order.adapter.TaoCanItemAdapter;
import com.estronger.shopmanage.ui.order.bean.BitmapItem;
import com.estronger.shopmanage.ui.order.bean.OrderAttributeBean;
import com.estronger.shopmanage.ui.order.bean.TaocanBean;
import com.estronger.shopmanage.ui.order.bean.TaocanitemBean;
import com.estronger.shopmanage.ui.order.bean.TaocanshuxBean;
import com.estronger.shopmanage.ui.order.bean.returnMsgEntity;
import com.estronger.shopmanage.ui.order.until.ActivityCollector;
import com.estronger.shopmanage.ui.order.until.DateDialog;
import com.estronger.shopmanage.ui.order.until.PictureUtil;
import com.estronger.shopmanage.ui.order.until.Tools;
import com.estronger.shopmanage.utils.PermissionUtils;
import com.soonfor.evaluate.activity.ShowPicActivity;
import com.soonfor.evaluate.tools.ImageUtils;
import com.estronger.shopmanage.utils.NetUtils;
import com.estronger.shopmanage.utils.PrefUtils;
import com.estronger.shopmanage.utils.ScreenUtils;
import com.estronger.shopmanage.utils.Toast;
import com.estronger.shopmanage.view.AppDialog;
import com.estronger.shopmanage.view.CustomGlridView;
import com.estronger.shopmanage.view.CustomListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.tbruyelle.rxpermissions2.Permission;

import org.json.JSONException;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jesse.nativelogger.NLogger;


/**
 * Created by DingYG on 2017-07-25.
 * 预订单录入
 */

public class OrderEntryActivity extends BaseActivity implements
        View.OnClickListener {

    private OrderEntryActivity mActivity;
    private View rootView;//根目录View
    private ScrollView sv_root;
    private Dialog dialog;
    private TextView tvfTitle, tvfRegion, tvfHouses, tvfAction, tvfMealType, tvfSerizes,
            tvfTexture, tvfColor, tvfProceeds, tvfYjazTime, tvfStyle, tvfSCustomRes;
    private EditText etfName, etfMobilePhone, etfDAddress, etfMoney, etfInputRemark;
    private RelativeLayout rlfSRegion, rlfSHouses, rlfSAction, rlfSMealType, rlfSSerizes,
            rlfSTextsure, rlfSColor, rlfSProceeds, rlfSelectTime, rlfSStyle, rlfSCustomRes;
    private RelativeLayout rlfAge;
    private TextView tvfAge;
    private LinearLayout llfOtherAttribute;
    private ImageView ivfBottom;
    private CustomListView lvfOther;
    private CustomGlridView gvfShowPics;
    private AddImagesAdapter addAdapter;
    private Map<Integer, String> inputMap;//手动输入的内容集合
    private Map<Integer, String> selMap;//选择后显示的内容集合
    private List<BitmapItem> bList;//图片集合
    private Button btfsaveorder;
    private int shuPosition = -1;//点击的是套餐的那个属性

    public static Map<Integer, ArrayList<TaocanBean>> TaocMap = new HashMap<>();//s所有套餐集合
    private List<LocalMedia> mSelectPicList;//选择的本地照片
    private BitmapItem defaultBitmap;//默认图片
    private int succeedNum = 0;//每次上传成功的图片数量
    private int faileNum = 0;//每次上传失败的图片数量
    public ArrayList<StringBean> imagePaths = new ArrayList<StringBean>();//上传成功后得到的网络路径集合
    TaoCanItemAdapter tsAdapter;
    ArrayList<TaocanitemBean> tcList = new ArrayList<>();
    private String customHouses = "";//自定义楼盘
    private String customRes = "";//自定义客户来源
    private boolean isUploadeding = false;//是否是在上传
    private ArrayList<String> imgPahts;
    private int cFailedNum = 0;//压缩失败的图片数量

    @Override
    protected void init() {
        clearVariable();
    }

    private void clearVariable() {
        if (Tools.sTcShuMap != null) {
            Tools.sTcShuMap.clear();
        } else {
            Tools.sTcShuMap = new HashMap<>();
        }
        inputMap = new HashMap<>();
        selMap = new HashMap<>();
        isUploadeding = false;
        getDefaultShoppcd();
    }

    /**
     * 获取门店默认的省市区
     */
    private void getDefaultShoppcd() {
        new Thread(loadRunnable).start();
    }

    Runnable loadRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                RequestParams params = new RequestParams();
                params.addBodyParameter("sf_action", "getshoppcd");
                params.addBodyParameter("usercode", MyApplication.getUserCode());
                connect(params, NetManager.ORDER_SELECT_DEFAULTSHOPPCD);
            }catch (Exception e){}
        }
    };

    @Override
    protected void initView() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mActivity = OrderEntryActivity.this;
        rootView = View.inflate(mActivity, R.layout.layout_activity_orderentry, null);
        setContentView(rootView);
        ivfBottom = (ImageView) findViewById(R.id.ivfBottom);
        tvfTitle = (TextView) findViewById(R.id.ab_title);
        tvfTitle.setText("预订单录入");
        btfsaveorder = (Button) mActivity.findViewById(R.id.tvf_save);
        sv_root = (ScrollView) findViewById(R.id.svfOrderEntry);
        findViewAndSetEvent(sv_root);
    }

    private void findViewAndSetEvent(View root) {
        etfName = (EditText) root.findViewById(R.id.etfInputName);
        etfMobilePhone = (EditText) root.findViewById(R.id.etfInputPhone);
        etfDAddress = (EditText) root.findViewById(R.id.etfInputAddress);
        etfMoney = (EditText) root.findViewById(R.id.etfInputMoney);
        etfInputRemark = (EditText) root.findViewById(R.id.etfInputRemark);

        tvfAge = (TextView) root.findViewById(R.id.tvfAge);
        tvfRegion = (TextView) root.findViewById(R.id.tvfRegion);
        tvfHouses = (TextView) root.findViewById(R.id.tvfHouses);
        tvfSCustomRes = (TextView) root.findViewById(R.id.tvfCustomerSource);
        tvfAction = (TextView) root.findViewById(R.id.tvfAction);
        tvfMealType = (TextView) root.findViewById(R.id.tvfMealType);
        tvfSerizes = (TextView) root.findViewById(R.id.tvfSeries);
        tvfTexture = (TextView) root.findViewById(R.id.tvfTexture);
        tvfColor = (TextView) root.findViewById(R.id.tvfColor);
        tvfProceeds = (TextView) root.findViewById(R.id.tvfProceedsType);
        tvfYjazTime = (TextView) root.findViewById(R.id.tvfYjazTime);
        tvfStyle = (TextView) root.findViewById(R.id.tvfStyle);

        rlfAge = (RelativeLayout) root.findViewById(R.id.rlfSelectAge);
        rlfSRegion = (RelativeLayout) root.findViewById(R.id.rlfSelectRegion);
        rlfSHouses = (RelativeLayout) root.findViewById(R.id.rlfSelectHouses);
        rlfSCustomRes = (RelativeLayout) root.findViewById(R.id.rlfSelectCustomerSource);
        rlfSAction = (RelativeLayout) root.findViewById(R.id.rlfSelectAction);
        rlfSMealType = (RelativeLayout) root.findViewById(R.id.rlfSelectMealType);
        rlfSSerizes = (RelativeLayout) root.findViewById(R.id.rlfSelectSeries);
        rlfSTextsure = (RelativeLayout) root.findViewById(R.id.rlfSelectTexture);
        rlfSColor = (RelativeLayout) root.findViewById(R.id.rlfSelectColor);
        rlfSProceeds = (RelativeLayout) root.findViewById(R.id.rlfSelectProceedsType);
        rlfSelectTime = (RelativeLayout) root.findViewById(R.id.rlfSelectTime);
        rlfSStyle = (RelativeLayout) root.findViewById(R.id.rlfSelectStyle);

        llfOtherAttribute = (LinearLayout) root.findViewById(R.id.llfOtherAttribute);
        lvfOther = (CustomListView) root.findViewById(R.id.clvOther);
        gvfShowPics = (CustomGlridView) root.findViewById(R.id.gvfAddCpImages);
        if (ScreenUtils.getNavigationBarHeight(mActivity) > 0) {
            ivfBottom.setVisibility(View.VISIBLE);
        } else {
            ivfBottom.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initAction() {
        super.initAction();
        btfsaveorder.setOnClickListener(this);
        rlfAge.setOnClickListener(this);
        rlfSRegion.setOnClickListener(this);
        rlfSHouses.setOnClickListener(this);
        rlfSCustomRes.setOnClickListener(this);
        rlfSAction.setOnClickListener(this);
        rlfSMealType.setOnClickListener(this);
        rlfSSerizes.setOnClickListener(this);
        rlfSTextsure.setOnClickListener(this);
        rlfSColor.setOnClickListener(this);
        rlfSProceeds.setOnClickListener(this);
        rlfSelectTime.setOnClickListener(this);
        rlfSStyle.setOnClickListener(this);

        etfName.addTextChangedListener(tWatcher);
        etfMobilePhone.addTextChangedListener(tWatcher);
        etfDAddress.addTextChangedListener(tWatcher);
        etfMoney.addTextChangedListener(tMoney);
        etfInputRemark.addTextChangedListener(tWatcher);

        etfInputRemark.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        v.getParent().requestDisallowInterceptTouchEvent(true);
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        v.getParent().requestDisallowInterceptTouchEvent(false);
                        break;
                }
                return false;
            }
        });
        tsAdapter = new TaoCanItemAdapter(mActivity);
        lvfOther.setAdapter(tsAdapter);
        initGridView();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    Runnable picRunnable = new Runnable() {
        @Override
        public void run() {
            // TODO 这里写上传逻辑
            try {
                if (mSelectPicList != null && mSelectPicList.size() > 0) {
                    Tools.canSNum = mSelectPicList.size();
                    bList.clear();
                    defaultBitmap = new BitmapItem();
                    defaultBitmap.setbPath(null);
                    defaultBitmap.setDelteState(0);
                    bList.add(defaultBitmap);
                    for (LocalMedia localMedia : mSelectPicList) {
                        String path = localMedia.getCompressPath();
                        if (TextUtils.isEmpty(path)) {
                            path = localMedia.getPath();
                        }
                        BitmapItem bitmapItem = new BitmapItem();
                        bitmapItem.setbPath(path);
                        bitmapItem.setDelteState(1);
                        bList.add(bList.size() - 1, bitmapItem);
                    }
                    RefreshListview();
                }
            } catch (Exception e) {
                e.fillInStackTrace();
            }
            dimssDialog2();
        }
    };

    class CompressTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... strings) {
            try {
                PictureUtil.compressImage(mActivity, strings[0], 60, new PictureUtil.Compress() {
                    @Override
                    public void done(String compressPath, String fileName) {
                        if (compressPath != null) {
                            BitmapItem bitmapItem = new BitmapItem();
                            bitmapItem.setbPath(compressPath);
                            bitmapItem.setDelteState(1);
                            bList.add(bList.size() - 1, bitmapItem);
                            RefreshListview();
                        } else {
                            cFailedNum++;
                        }
                    }
                });

            } catch (FileNotFoundException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (cFailedNum + bList.size() - 1 == mSelectPicList.size()) {
                dimssDialog2();
                mSelectPicList.clear();
                if (cFailedNum > 0) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.show(mActivity, "有" + cFailedNum + "张图片读取失败，请重新选择！", Toast.LENGTH_SHORT);
                            cFailedNum = 0;
                        }
                    });
                }
            }
        }
    }

    /* 初始化GridView 显示图片*/
    private void initGridView() {
        addAdapter = new AddImagesAdapter(mActivity, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int selectpost = (int) v.getTag();
                bList.remove(selectpost);
                RefreshListview();
            }
        });
        gvfShowPics.setAdapter(addAdapter);
        bList = new ArrayList<>();
        defaultBitmap = new BitmapItem();
        defaultBitmap.setbPath(null);
        defaultBitmap.setDelteState(0);
        bList.add(defaultBitmap);
        RefreshListview();
        gvfShowPics.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                if (position == 12) {
                    Toast.show(mActivity, "最多只能选择12张！", Toast.LENGTH_SHORT);
                    return;
                }
                if (position == addAdapter.getCount() - 1) {
                    Tools.canSNum = 12 - bList.size() + 1;
                    ImageUtils.choosePicture(mActivity, PictureConfig.CHOOSE_REQUEST, Tools.canSNum, mSelectPicList);
                } else {
                    Bundle bundle1 = new Bundle();
                    bundle1.putStringArrayList("piclists", imgPahts);
                    bundle1.putInt("position", position);
                    bundle1.putBoolean("ISLOCALPIC", true);
                    Intent intent = new Intent(mActivity, ShowPicActivity.class);
                    intent.putExtras(bundle1);
                    mActivity.startActivity(intent);
                }
            }
        });
    }

    @Override
    public void onBackViewClick(View view) {
        if (isChanged()) {
            dialog = AppDialog.createEjectNoticeDialog(mActivity, this);
            dialog.show();
        } else {
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        try {
            String tcid = "0";
            if (Tools.sTaocan != null) {
                tcid = Tools.ToDefaultString(Tools.sTaocan.getTcId());
            }
            switch (v.getId()) {
                case R.id.tvf_save:
                    try {
                        savePremise();
                    } catch (Exception e) {
                        e.getMessage();
                    }
                    break;
                case R.id.rlfSelectAge://年龄
                    showDialog("请稍侯...", true);
                    Tools.setEndableToRl(rlfAge);
                    RequestParams params0 = new RequestParams();
                    params0.addBodyParameter("sf_action", "getagephases");
                    params0.addBodyParameter("usercode", MyApplication.getUserCode());
                    connect(params0, NetManager.ORDER_SELECT_AGE);
                    break;
                case R.id.rlfSelectRegion://地区
                    showDialog("请稍侯...", true);
                    Tools.setEndableToRl(rlfSRegion);
                    if (Tools.sCity == null) {
                        RequestParams params = new RequestParams();
                        params.addBodyParameter("sf_action", "getcitys");
                        params.addBodyParameter("usercode", MyApplication.getUserCode());
                        connect(params, NetManager.ORDER_SELECT_CITY);
                    } else if (Tools.sCity.getAttId() != null) {
                        RequestParams params = new RequestParams();
                        params.addBodyParameter("sf_action", "getdistricts");
                        params.addBodyParameter("usercode", MyApplication.getUserCode());
                        params.addBodyParameter("cityid", Tools.sCity.getAttId());
                        connect(params, NetManager.ORDER_SELECT_COUNTRY);
                    }
                    break;
                case R.id.rlfSelectHouses://楼盘（需新增楼盘）
                    Tools.setEndableToRl(rlfSHouses);
                    if (Tools.ToString(tvfRegion.getText().toString()).equals("")) {
                        toastShow(2, "客户地区");
                        return;
                    }
                    if (SelectHousesActivity.class != null && ActivityCollector.isActivityExist(SelectHousesActivity.class)) {
                        return;
                    }
                    Bundle bundle1 = new Bundle();
                    bundle1.putInt(PrefUtils.WHITCHSHUXING, 1);
                    mActivity.startActivityResult(SelectHousesActivity.class,
                            bundle1, Tools.REQUEST_CODE_CHOISE_HOUSES);
                    break;
                case R.id.rlfSelectCustomerSource://客户来源
                    Tools.setEndableToRl(rlfSCustomRes);
                    if (SelectHousesActivity.class != null && ActivityCollector.isActivityExist(SelectHousesActivity.class)) {
                        return;
                    }
                    Bundle bundle22 = new Bundle();
                    bundle22.putInt(PrefUtils.WHITCHSHUXING, 6);
                    mActivity.startActivityResult(SelectHousesActivity.class,
                            bundle22, Tools.REQUEST_CODE_CHOISE_CUSTOMRES);
                    break;
                case R.id.rlfSelectSeries://系列
                    showDialog("请稍侯...", true);
                    Tools.setEndableToRl(rlfSSerizes);
                    RequestParams params1 = new RequestParams();
                    params1.addBodyParameter("sf_action", "getkits");
                    params1.addBodyParameter("usercode", MyApplication.getUserCode());
                    params1.addBodyParameter("activitysuiteid", tcid);
                    connect(params1, NetManager.ORDER_SELECT_SERIZES);
                    break;
                case R.id.rlfSelectStyle://款式
                    showDialog("请稍侯...", true);
                    Tools.setEndableToRl(rlfSStyle);
                    RequestParams params11 = new RequestParams();
                    params11.addBodyParameter("sf_action", "getstyles");
                    params11.addBodyParameter("usercode", MyApplication.getUserCode());
                    params11.addBodyParameter("kitid", Tools.ToDefaultString(selMap.get(5)));
                    connect(params11, NetManager.ORDER_SELECT_STYLES);
                    break;
                case R.id.rlfSelectTexture://材质
                    showDialog("请稍侯...", true);
                    Tools.setEndableToRl(rlfSTextsure);
                    RequestParams params2 = new RequestParams();
                    params2.addBodyParameter("sf_action", "getrmqlts");
                    params2.addBodyParameter("usercode", MyApplication.getUserCode());
                    params2.addBodyParameter("activitysuiteid", tcid);
                    params2.addBodyParameter("styleid", Tools.ToDefaultString(selMap.get(6)));
                    connect(params2, NetManager.ORDER_SELECT_TEXTTURE);
                    break;
                case R.id.rlfSelectAction://活动
                    showDialog("请稍侯...", true);
                    Tools.setEndableToRl(rlfSAction);
                    RequestParams params3 = new RequestParams();
                    params3.addBodyParameter("sf_action", "getactivitys");
                    params3.addBodyParameter("usercode", MyApplication.getUserCode());
                    connect(params3, NetManager.ORDER_SELECT_ACTION);
                    break;
                case R.id.rlfSelectMealType://套餐类型
                    showDialog("请稍侯...", true);
                    Tools.setEndableToRl(rlfSMealType);
                    RequestParams params4 = new RequestParams();
                    params4.addBodyParameter("sf_action", "getactivitysuites");
                    params4.addBodyParameter("usercode", MyApplication.getUserCode());
                    params4.addBodyParameter("activityid", Tools.ToDefaultString(selMap.get(3)));
                    connect(params4, NetManager.ORDER_SELECT_MEALTYPE);
                    break;
                case R.id.rlfSelectColor://颜色
                    showDialog("请稍侯...", true);
                    Tools.setEndableToRl(rlfSColor);
                    RequestParams params5 = new RequestParams();
                    params5.addBodyParameter("sf_action", "getclrs");
                    params5.addBodyParameter("usercode", MyApplication.getUserCode());
                    params5.addBodyParameter("activitysuiteid", tcid);
                    params5.addBodyParameter("styleid", Tools.ToDefaultString(selMap.get(6)));
                    connect(params5, NetManager.ORDER_SELECT_COLOR);
                    break;
                case R.id.rlfSelectProceedsType://收款类型
                    showDialog("请稍侯...", true);
                    Tools.setEndableToRl(rlfSProceeds);
                    RequestParams params7 = new RequestParams();
                    params7.addBodyParameter("sf_action", "getreceivetypes");
                    params7.addBodyParameter("usercode", MyApplication.getUserCode());
                    connect(params7, NetManager.ORDER_SELECT_GATHERING);
                    break;
                case R.id.rlfSelectTime://预计安装日期
                    Tools.setEndableToRl(rlfSelectTime);
                    DateDialog.yjanzPicker(this, "预计安装日期", tvfYjazTime).show();
                    break;
                case R.id.save://保存
                    dialog.dismiss();
                    if (!NetUtils.isNetworkConnected(mActivity)) {
                        Toast.show(mActivity, "当前无网络链接！", 2000);
                        return;
                    }
                    deleAllPics();
                    imagePaths.clear();
                    isUploadeding = true;
                    if (bList.size() > 1) {
                        uploadImages(bList.get(0).getbPath());
                    } else {
                        showDialog("请稍侯...", true);
                        submitAdvanceOrder();
                    }
                    break;
                case R.id.ok://确定
                    dialog.dismiss();
                    finish();
                    break;
                case R.id.cancel:
                    dialog.dismiss();
                    break;
            }
        } catch (Exception e) {
        }
    }

    private TextWatcher tWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            inputMap.put(0, Tools.ToString(etfName.getText().toString()));
            inputMap.put(1, Tools.ToString(etfMobilePhone.getText().toString()));
            inputMap.put(2, Tools.ToString(etfDAddress.getText().toString()));
            inputMap.put(4, Tools.ToString(etfInputRemark.getText().toString()));
        }
    };
    private TextWatcher tMoney = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            try {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 6) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 7);
                        etfMoney.setText(s);
                        etfMoney.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    etfMoney.setText(s);
                    etfMoney.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        etfMoney.setText(s.subSequence(0, 1));
                        etfMoney.setSelection(1);
                        return;
                    }
                }
            } catch (Exception e) {
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            String result = s.toString();
            if (result.length() - result.indexOf(".") > 7) {
                result = result.substring(0, result.length() - 1);
            }
            inputMap.put(3, result);
        }
    };

    /**
     * 网络请求
     */
    //成功
    @Override
    protected void onNetSuccess(int code, String result) {
        super.onNetSuccess(code, result);
        switch (code) {
            case NetManager.ORDER_SELECT_DEFAULTSHOPPCD:
                Tools.dShop = Tools.getDefaultShopData(result);
                if (Tools.dShop != null) {
                    tvfRegion.setText(Tools.dShop.getCityname() + Tools.dShop.getDistrictname());
                    selMap.put(0, Tools.dShop.getCityid());
                    selMap.put(1, Tools.dShop.getDistrictid());
                    OrderAttributeBean city = new OrderAttributeBean();
                    city.setAttId(Tools.dShop.getCityid());
                    city.setAttName(Tools.dShop.getCityname());
                    Tools.sCity = city;
                    OrderAttributeBean count = new OrderAttributeBean();
                    count.setAttId(Tools.dShop.getDistrictid());
                    count.setAttName(Tools.dShop.getDistrictname());
                    Tools.sCountry = count;
                }
                break;
            case NetManager.ORDER_SELECT_CITY:
                ArrayList<OrderAttributeBean> cityDatas = Tools.getResponseData(result, "cityid", "cityname");
                if (cityDatas == null || cityDatas.size() == 0) {
                    if (cityDatas.size() == 0) {
                        toastShow(-1, "未获取到城市地区信息");
                    } else {
                        toastShow(1, Tools.dShop.getProvincename() + "的城市");
                    }
                } else {
                    if (SelectRegionActivity.class != null && ActivityCollector.isActivityExist(SelectRegionActivity.class)) {
                        return;
                    }
                    Bundle bundle = new Bundle();
                    bundle.putInt("CITYORCOUNTRY", 0);
                    bundle.putParcelableArrayList("BUNDLE_CITY", cityDatas);
                    mActivity.startActivityResult(SelectRegionActivity.class, bundle,
                            Tools.REQUEST_CODE_CHOISE_REGION);
                }
                break;
            case NetManager.ORDER_SELECT_COUNTRY:
                ArrayList<OrderAttributeBean> countDatas = Tools.getResponseData(result, "districtid", "districtname");
                if (countDatas == null || countDatas.size() == 0) {
                    toastShow(1, Tools.sCity.getAttName() + "的区县");
                } else {
                    if (SelectRegionActivity.class != null && ActivityCollector.isActivityExist(SelectRegionActivity.class)) {
                        return;
                    }
                    Bundle bundle = new Bundle();
                    bundle.putInt("CITYORCOUNTRY", 1);
                    bundle.putParcelableArrayList("BUNDLE_COUNTRY", countDatas);
                    mActivity.startActivityResult(SelectRegionActivity.class, bundle,
                            Tools.REQUEST_CODE_CHOISE_REGION);
                }
                break;
            case NetManager.ORDER_SELECT_AGE:
                dimssDialog();
                ArrayList<OrderAttributeBean> ages = Tools.getResponseData(result, "id", "aphasedesc");
                if (ages == null || ages.size() == 0) {
                    toastShow(1, "年龄");
                } else {
                    String checkedId = "";
                    try{
                        checkedId = selMap.get(100);
                    }catch (Exception e){}
                    SelectActionActivity.openActivity(mActivity, 3, ages, checkedId, Tools.REQUEST_CODE_CHOISE_AGE);
                }
                break;
            case NetManager.ORDER_SELECT_ACTION:
                ArrayList<OrderAttributeBean> actionDatas = Tools.getResponseData(result, "activityid", "activitytitle");
                if (actionDatas == null || actionDatas.size() == 0) {
                    toastShow(1, "活动");
                } else {
                    String checkedId = "";
                    try{
                        checkedId = selMap.get(3);
                    }catch (Exception e){}
                    SelectActionActivity.openActivity(mActivity, 4, actionDatas, checkedId, Tools.REQUEST_CODE_CHOISE_ACTION);
                }
                break;
            case NetManager.ORDER_SELECT_MEALTYPE:
                ArrayList<TaocanBean> tcData = Tools.getTaocanData(result);
                if (tcData == null || tcData.size() == 0) {
                    toastShow(1, "套餐");
                } else {
                    SelectActionActivity.openActivity(mActivity, tcData);
                }
                break;
            case NetManager.ORDER_SELECT_SERIZES:
                ArrayList<OrderAttributeBean> serDatas = Tools.getResponseData(result, "kitid", "kitname");
                if (serDatas == null || serDatas.size() == 0) {
                    toastShow(1, "系列");
                } else {
                    if (SelectHousesActivity.class != null && ActivityCollector.isActivityExist(SelectHousesActivity.class)) {
                        return;
                    }
                    Bundle bundle2 = new Bundle();
                    bundle2.putParcelableArrayList(PrefUtils.BUNDLEARRAY, serDatas);
                    bundle2.putInt(PrefUtils.WHITCHSHUXING, 2);
                    mActivity.startActivityResult(SelectHousesActivity.class,
                            bundle2, Tools.REQUEST_CODE_CHOISE_SERIZES);
                }
                break;
            case NetManager.ORDER_SELECT_STYLES:
                ArrayList<OrderAttributeBean> styDatas = Tools.getResponseData(result, "styleid", "stylename", "kitid", "kitname");
                if (styDatas == null || styDatas.size() == 0) {
                    toastShow(1, "款式");
                } else {
                    if (SelectHousesActivity.class != null && ActivityCollector.isActivityExist(SelectHousesActivity.class)) {
                        return;
                    }
                    Bundle bundle21 = new Bundle();
                    bundle21.putParcelableArrayList(PrefUtils.BUNDLEARRAY, styDatas);
                    bundle21.putInt(PrefUtils.WHITCHSHUXING, 3);
                    mActivity.startActivityResult(SelectHousesActivity.class,
                            bundle21, Tools.REQUEST_CODE_CHOISE_STYLES);
                }
                break;
            case NetManager.ORDER_SELECT_TEXTTURE:
                ArrayList<OrderAttributeBean> rmqDatas = Tools.getResponseData(result, "rmqltid", "rmqltname");
                if (rmqDatas == null || rmqDatas.size() == 0) {
                    toastShow(1, "树种");
                } else {
                    if (SelectHousesActivity.class != null && ActivityCollector.isActivityExist(SelectHousesActivity.class)) {
                        return;
                    }
                    Bundle bundle2 = new Bundle();
                    bundle2.putParcelableArrayList(PrefUtils.BUNDLEARRAY, rmqDatas);
                    bundle2.putInt(PrefUtils.WHITCHSHUXING, 4);
                    mActivity.startActivityResult(SelectHousesActivity.class,
                            bundle2, Tools.REQUEST_CODE_CHOISE_TEXTURE);
                }
                break;
            case NetManager.ORDER_SELECT_COLOR:
                ArrayList<OrderAttributeBean> colorDatas = Tools.getResponseData(result, "clrid", "clrname");
                if (colorDatas == null || colorDatas.size() == 0) {
                    toastShow(1, "颜色");
                } else {
                    if (SelectHousesActivity.class != null && ActivityCollector.isActivityExist(SelectHousesActivity.class)) {
                        return;
                    }
                    Bundle bundle4 = new Bundle();
                    bundle4.putParcelableArrayList(PrefUtils.BUNDLEARRAY, colorDatas);
                    bundle4.putInt(PrefUtils.WHITCHSHUXING, 5);
                    mActivity.startActivityResult(SelectHousesActivity.class,
                            bundle4, Tools.REQUEST_CODE_CHOISE_COLOR);
                }
                break;
            case NetManager.ORDER_SELECT_GATHERING:
                ArrayList<OrderAttributeBean> gatherDatas = Tools.getResponseData(result, "code", "desc");
                if (gatherDatas == null || gatherDatas.size() == 0) {
                    toastShow(1, "收款类型");
                } else {
                    String checkedId = "";
                    try{
                        checkedId = selMap.get(9);
                    }catch (Exception e){}
                    SelectActionActivity.openActivity(mActivity, 6, gatherDatas, checkedId, Tools.REQUEST_CODE_CHOISE_GATHERINGTYPE);
                }
                break;
            case NetManager.ORDER_SELECT_MEALTYPE_SHUX://其它属性
                ArrayList<TaocanshuxBean> otherDatas = Tools.getTcChildData(result);
                if (otherDatas == null || otherDatas.size() == 0) {
                    toastShow(1, Tools.sOneTao.getAttName());
                } else {
                    if (SelectHousesActivity.class != null && ActivityCollector.isActivityExist(SelectHousesActivity.class)) {
                        return;
                    }
                    Bundle bundle7 = new Bundle();
                    bundle7.putParcelableArrayList(PrefUtils.BUNDLEARRAY, otherDatas);
                    bundle7.putInt(PrefUtils.WHITCHSHUXING, 8);
                    mActivity.startActivityResult(SelectHousesActivity.class,
                            bundle7, Tools.REQUEST_CODE_CHOISE_TAOCANOTHERSHUX);

                }
                break;
        }
    }

    @Override
    protected void onNetErorr(int code, String msg) {
        dimssDialog();
        super.onNetErorr(code, msg);
        if (code == NetManager.ORDER_SELECT_DEFAULTSHOPPCD) {
            // toastShow(1, "门店的默认省市区");
        } else {
            toastShow(3, msg);
        }
    }

    /**
     * 清空材质和颜色
     */
    private void clearTandColor(int clearNum) {
        tvfTexture.setText("");
        tvfColor.setText("");
        selMap.put(7, "0");
        selMap.put(8, "0");
        switch (clearNum) {
            case 2:
                break;
            case 3:
                tvfStyle.setText("");
                selMap.put(6, "0");
                break;
            case 4:
                tvfSerizes.setText("");
                tvfStyle.setText("");
                selMap.put(5, "0");
                selMap.put(6, "0");
                break;
            case 5:
                tvfMealType.setText("");
                tvfSerizes.setText("");
                tvfStyle.setText("");
                selMap.put(4, "0");
                selMap.put(5, "0");
                selMap.put(6, "0");
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Tools.REQUEST_CODE_CHOISE_AGE:
                    OrderAttributeBean ageD = (OrderAttributeBean) data.getParcelableExtra("SELECT_AGE");
                    tvfAge.setText(Tools.ToString(ageD.getAttName()));
                    selMap.put(100, Tools.ToDefaultString(ageD.getAttId()));
                    break;
                case Tools.REQUEST_CODE_CHOISE_REGION:
                    try {
                        tvfRegion.setText(Tools.sCity.getAttName() + Tools.sCountry.getAttName());
                        selMap.put(0, Tools.ToDefaultString(Tools.sCity.getAttId()));
                        selMap.put(1, Tools.ToDefaultString(Tools.sCountry.getAttId()));
                        tvfHouses.setText("");
                        etfDAddress.setText("");
                        selMap.put(2, "0");
                    } catch (Exception e) {
                    }
                    break;
                case Tools.REQUEST_CODE_CHOISE_HOUSES:
                    OrderAttributeBean shuHouses = (OrderAttributeBean) data.getParcelableExtra("SELECT_HOUSES");
                    tvfHouses.setText(Tools.ToString(shuHouses.getAttName()));
                    selMap.put(2, Tools.ToDefaultString(shuHouses.getAttId()));
                    if (shuHouses.getAttId() == null) {//自定义的楼盘
                        customHouses = shuHouses.getAttName();
                    }
                    break;
                case Tools.REQUEST_CODE_CHOISE_CUSTOMRES:
                    OrderAttributeBean cRes = (OrderAttributeBean) data.getParcelableExtra("SELECT_CUSTOMRES");
                    tvfSCustomRes.setText(Tools.ToString(cRes.getAttName()));
                    selMap.put(101, Tools.ToDefaultString(cRes.getAttId()));
                    if (cRes.getAttId() == null) {//自定义的客户来源
                        customRes = cRes.getAttName();
                    }
                    break;
                case Tools.REQUEST_CODE_CHOISE_ACTION:
                    OrderAttributeBean action = (OrderAttributeBean) data.getParcelableExtra("SELECT_ACTION");
                    if (Tools.sAction != null && action != null && Tools.sAction.getAttId().equals(action.getAttId())
                            && Tools.sAction.getAttName().equals(action.getAttName())) {
                        return;
                    }
                    Tools.sAction = action;
                    tvfAction.setText(Tools.ToString(action.getAttName()));
                    selMap.put(3, Tools.ToDefaultString(action.getAttId()));
                    clearTandColor(5);
                    if (tcList != null) {
                        tcList.clear();
                    }
                    showTCOtherShu(tcList);
                    break;
                case Tools.REQUEST_CODE_CHOISE_MEALTYPE:
                    TaocanBean tc = (TaocanBean) data.getSerializableExtra("SELECT_TAOCAN");
                    if (Tools.sTaocan != null && tc != null && Tools.sTaocan.getTcId().equals(tc.getTcId())
                            && Tools.sTaocan.getTcName().equals(tc.getTcName()) && !Tools.ToDefaultString(tvfMealType.getText().toString()).equals("0")) {
                        return;
                    }
                    if (tcList != null) {
                        tcList.clear();
                    }
                    tcList = tc.getTcsxList();
                    showTCOtherShu(tcList);
                    tvfMealType.setText(Tools.ToString(tc.getTcName()));
                    selMap.put(4, Tools.ToDefaultString(tc.getTcId()));
                    Tools.sTaocan = tc;
                    Tools.sTcShuMap.clear();
                    clearTandColor(4);
                    break;
                case Tools.REQUEST_CODE_CHOISE_SERIZES:
                    OrderAttributeBean serizes = (OrderAttributeBean) data.getParcelableExtra("SELECT_KITS");
                    if (Tools.sKit != null && serizes != null && Tools.sKit.getAttId().equals(serizes.getAttId())
                            && Tools.sKit.getAttName().equals(serizes.getAttName()) && !Tools.ToDefaultString(tvfSerizes.getText().toString()).equals("0")) {
                        return;
                    }
                    tvfSerizes.setText(Tools.ToString(serizes.getAttName()));
                    selMap.put(5, Tools.ToDefaultString(serizes.getAttId()));
                    Tools.sKit = serizes;
                    clearTandColor(3);
                    break;
                case Tools.REQUEST_CODE_CHOISE_STYLES:
                    OrderAttributeBean styles = (OrderAttributeBean) data.getParcelableExtra("SELECT_STYLES");
                    if (Tools.sStyle != null && styles != null && Tools.sStyle.getAttId().equals(styles.getAttId())
                            && Tools.sStyle.getAttName().equals(styles.getAttName()) && !Tools.ToDefaultString(tvfStyle.getText().toString()).equals("0")) {
                        return;
                    }
                    tvfStyle.setText(Tools.ToString(styles.getAttName()));
                    selMap.put(6, Tools.ToDefaultString(styles.getAttId()));
                    if (!Tools.ToDefaultString(styles.getAffiliatedid()).equals("0")) {
                        selMap.put(5, styles.getAffiliatedid());
                        if (!Tools.ToString(styles.getAffiliatedName()).equals("")) {
                            tvfSerizes.setText(styles.getAffiliatedName());
                        }
                    }
                    Tools.sStyle = styles;
                    clearTandColor(2);
                    break;
                case Tools.REQUEST_CODE_CHOISE_TEXTURE:
                    OrderAttributeBean texture = (OrderAttributeBean) data.getParcelableExtra("SELECT_RMQLTS");
                    tvfTexture.setText(Tools.ToString(texture.getAttName()));
                    selMap.put(7, Tools.ToDefaultString(texture.getAttId()));
                    break;
                case Tools.REQUEST_CODE_CHOISE_COLOR:
                    OrderAttributeBean color = (OrderAttributeBean) data.getParcelableExtra("SELECT_COLOR");
                    tvfColor.setText(Tools.ToString(color.getAttName()));
                    selMap.put(8, Tools.ToDefaultString(color.getAttId()));
                    break;
                case Tools.REQUEST_CODE_CHOISE_GATHERINGTYPE:
                    OrderAttributeBean gaterType = (OrderAttributeBean) data.getParcelableExtra("SELECT_GATHERINGTYPE");
                    tvfProceeds.setText(Tools.ToString(gaterType.getAttName()));
                    selMap.put(9, Tools.ToDefaultString(gaterType.getAttId()));
                    break;
                case Tools.REQUEST_CODE_CHOISE_TAOCANOTHERSHUX:
                    TaocanshuxBean shuBean = (TaocanshuxBean) data.getParcelableExtra("TAOCANSHUX_SELECT");
                    Tools.sTcShuMap.put(Tools.sOneTao.getAttId(), shuBean);
                    if (shuPosition != -1) {
                        View view = lvfOther.getChildAt(shuPosition);
                        TextView textShu = (TextView) view.findViewById(R.id.tvfTcShux);
                        textShu.setText(shuBean.getCodename());
                    }
                    break;
                case PictureConfig.CHOOSE_REQUEST:
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            sv_root.fullScroll(ScrollView.FOCUS_DOWN);
                        }
                    });
                    if (data != null) {
                        List<LocalMedia> medias = PictureSelector.obtainMultipleResult(data);
                        if (medias != null && medias.size() > 0) {
                            mSelectPicList = medias;
                            showDialog2("正在生成压缩图片，请稍候...", false);
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    dimssDialog2();
                                }
                            }, 15 * 1000);
                            new Thread(picRunnable).start();
                        } else {
                            Toast.show(mActivity, "未选择任何图片", 2000);
                        }
                    }
                    break;
            }
        }
    }


    //适配器更新数据
    private void RefreshListview() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                if (imgPahts == null) {
                    imgPahts = new ArrayList<>();
                } else {
                    imgPahts.clear();
                }
                if (bList.size() >= 2) {
                    for (int i = 0; i < bList.size() - 1; i++) {
                        imgPahts.add(bList.get(i).getbPath());
                    }
                }
                addAdapter.appendData(bList, true);
            }
        });
    }

    //界面是否有修改
    private boolean isChanged() {
        if ((inputMap == null || inputMap.size() == 0)
                && Tools.ToString(tvfAge.getText().toString()).equals("")
                && Tools.ToString(tvfHouses.getText().toString()).equals("")
                && Tools.ToString(tvfAction.getText().toString()).equals("")
                && Tools.ToString(tvfMealType.getText().toString()).equals("")
                && Tools.ToString(tvfSerizes.getText().toString()).equals("")
                && Tools.ToString(tvfStyle.getText().toString()).equals("")
                && Tools.ToString(tvfTexture.getText().toString()).equals("")
                && Tools.ToString(tvfColor.getText().toString()).equals("")
                && Tools.ToString(tvfProceeds.getText().toString()).equals("")
                && Tools.ToString(tvfYjazTime.getText().toString()).equals("")) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 提交预订单前的操作
     */
    private void savePremise() {
        if (isNullFromEditText(etfName)) {
            toastShow(0, "客户姓名");
            return;
        }
        if (isNullFromEditText(etfMobilePhone)) {
            toastShow(0, "客户手机号码");
            return;
        }
        if (!Tools.isMobileNO(etfMobilePhone.getText().toString())) {
            toastShow(0, "正确的手机号码");
            return;
        }
        if (isNullFromTextView(tvfAge)) {
            toastShow(2, "客户所属年龄段");
            return;
        }
        if (isNullFromTextView(tvfRegion)) {
            toastShow(2, "客户所在的地区");
            return;
        }
        if (isNullFromEditText(etfDAddress)) {
            toastShow(0, "客户详细地址");
            return;
        }
        if (tcList != null && tcList.size() > 0) {
            TaoCanItemAdapter tsAdapter = (TaoCanItemAdapter) lvfOther.getAdapter();
            if (tsAdapter != null) {
                for (int i = 0; i < tsAdapter.getCount(); i++) {
                    View view = lvfOther.getChildAt(i);
                    TaocanitemBean itemBean = tsAdapter.getItem(i);
                    TextView tvSelect = (TextView) view.findViewById(R.id.tvfTcShux);
                    if (isNullFromTextView(tvSelect)) {
                        toastShow(3, "请设置" + itemBean.getAttName() + "的属性值");
                        return;
                    }
                }
            }
        }
        if (isNullFromTextView(tvfProceeds)) {
            toastShow(2, "收款类型");
            return;
        }
        if (isNullFromEditText(etfMoney)) {
            toastShow(0, "金额");
            return;
        }
        if (isNullFromTextView(tvfYjazTime)) {
            toastShow(2, "预计安装时间");
            return;
        }
        if (isUploadeding) {
            Toast.show(mActivity, "正在上传图片,请稍候再点击提交！", Toast.LENGTH_SHORT);
            return;
        }
        dialog = AppDialog.createSaveorderDialog(mActivity, this);
        dialog.show();
    }

    //提交预订单
    private void submitAdvanceOrder() {
        //图片上传成功后再保存
        new Thread(commitRunnable).start();
    }

    Runnable commitRunnable = new Runnable() {
        @Override
        public void run() {
            // TODO 这里写上传逻辑
            try {
                RequestParams params = new RequestParams();
                params.addBodyParameter("sf_action", "addpreord");
                params.addBodyParameter("usercode", MyApplication.getUserCode());
                params.addBodyParameter("ordData", getParams_ordData());
                params.addBodyParameter("codes", getParams_codes());
                params.addBodyParameter("imgs", Tools.List_2json(imagePaths));
                String url = MyApplication.getApplication().getSERVER_URL()
                        + "/web/common/API/apphandler.ashx";
                HttpUtils httpUtils = new HttpUtils();
                httpUtils.configTimeout(10 * 1000).configSoTimeout(10 * 1000).configRequestRetryCount(3);
                httpUtils.send(HttpRequest.HttpMethod.POST, url, params,
                        new RequestCallBack<String>() {

                            @Override
                            public void onSuccess(ResponseInfo<String> responseInfo) {
                                dimssDialog();
                                isUploadeding = false;
                                try {
                                    returnMsgEntity re = Tools.jsonResolve_returnMsgEntity(responseInfo.result);
                                    if (re != null) {
                                        if (re.getSuccess()) {
                                            toastShow(3, "预订单提交成功");
                                            finish();
                                        } else {
                                            toastShow(3, "预订单提交失败：" + re.getMsg());
                                        }
                                    } else {
                                        toastShow(3, "预订单提交失败");
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    toastShow(3, "预订单提交失败");
                                }
                            }

                            @Override
                            public void onFailure(HttpException error, String msg) {
                                dimssDialog();
                                isUploadeding = false;
                                toastShow(3, "预订单提交失败");
                            }
                        });
            }catch (Exception e){}

        }
    };

    /**
     * 展示套餐的其它属性
     */
    private void showTCOtherShu(ArrayList<TaocanitemBean> tcsList) {

        if (tcsList == null || tcsList.size() == 0) {
            tsAdapter.appendData(tcsList);
            llfOtherAttribute.setVisibility(View.GONE);
            return;
        } else {
            llfOtherAttribute.setVisibility(View.VISIBLE);
            tsAdapter.appendData(tcsList);
            lvfOther.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Tools.setEndableToListV(lvfOther);
                    TaocanitemBean itemBean = tsAdapter.getItem(position);
                    Tools.sOneTao = itemBean;
                    shuPosition = position;
                    RequestParams params8 = new RequestParams();
                    params8.addBodyParameter("sf_action", "getcodes");
                    params8.addBodyParameter("usercode", MyApplication.getUserCode());
                    params8.addBodyParameter("activitysuitepropitemid", itemBean.getAttId());
                    connect(params8, NetManager.ORDER_SELECT_MEALTYPE_SHUX);
                }
            });

        }

    }

    /**
     * 获取参数列表1
     */
    private String getParams_ordData() {//获取ordData字段对应的参数
        HashMap<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("cstname", Tools.ToDefaultString(inputMap.get(0)));
        paramMap.put("cstmobile", Tools.ToDefaultString(inputMap.get(1)));
        paramMap.put("cityid", Tools.ToDefaultString(selMap.get(0)));
        paramMap.put("districtid", Tools.ToDefaultString(selMap.get(1)));
        paramMap.put("buildid", Tools.ToDefaultString(selMap.get(2)));
        paramMap.put("buildname", Tools.ToString(customHouses));
        paramMap.put("deliveradd", Tools.ToDefaultString(inputMap.get(2)));
        paramMap.put("activityid", Tools.ToDefaultString(selMap.get(3)));
        paramMap.put("activitysuiteid", Tools.ToDefaultString(selMap.get(4)));
        paramMap.put("kitid", Tools.ToDefaultString(selMap.get(5)));
        paramMap.put("styleid", Tools.ToDefaultString(selMap.get(6)));
        paramMap.put("rmqltid", Tools.ToDefaultString(selMap.get(7)));
        paramMap.put("clrid", Tools.ToDefaultString(selMap.get(8)));
        paramMap.put("receivetype", Tools.ToDefaultString(selMap.get(9)));
        paramMap.put("receivedamt", Tools.ToDefaultString(inputMap.get(3)));
        paramMap.put("orddate", Tools.sYjazdate);
        paramMap.put("remark", Tools.ToDefaultString(inputMap.get(4)));
        paramMap.put("agephase", Tools.ToDefaultString(selMap.get(100)));
        paramMap.put("origin", Tools.ToDefaultString(selMap.get(101)));
        paramMap.put("origindesc", Tools.ToString(customRes));
        return Tools.map2json(paramMap);
    }

    /**
     * 获取参数列表2
     */
    private String getParams_codes() {//获取codes字段对应的参数（套餐属性）
        List<Map<String, String>> paramList = new ArrayList<Map<String, String>>();
        for (Map.Entry<String, TaocanshuxBean> entry : Tools.sTcShuMap.entrySet()) {
            TaocanshuxBean tBean = entry.getValue();
            Map<String, String> listMap = new HashMap<>();
            listMap.put("propertyid", Tools.ToDefaultString(tBean.getProid()));
            listMap.put("propertycode", Tools.ToDefaultString(tBean.getProcode()));
            listMap.put("code", Tools.ToDefaultString(tBean.getCode()));
            listMap.put("codeid", Tools.ToDefaultString(tBean.getCodeid()));
            paramList.add(listMap);

        }
        String resultJson = null;
        try {
            resultJson = Tools.ListmapToJSON(paramList);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (paramList.size() == 0) {
            return "";
        }
        return resultJson;
    }

    //Toast
    private void toastShow(int type, String showContext) {
        switch (type) {
            case 0://未输入提示语
                Toast.show(mActivity, "请输入" + showContext + "！", Toast.LENGTH_SHORT);
                break;
            case 1: //未获取提示语
                Toast.show(mActivity, "未获取到" + showContext + "信息！", Toast.LENGTH_SHORT);
                break;
            case 2://未选择提示语
                Toast.show(mActivity, "请选择" + showContext + "！", Toast.LENGTH_SHORT);
                break;
            default:
                Toast.show(mActivity, showContext + "！", Toast.LENGTH_SHORT);
                break;
        }
    }

    //判断textView的内容是否为空
    private boolean isNullFromTextView(TextView tv) {
        return Tools.ToString(tv.getText().toString()).equals("");
    }

    //获取EditText的内容
    private boolean isNullFromEditText(EditText et) {
        return Tools.ToString(et.getText().toString()).equals("");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (isChanged()) {
                dialog = AppDialog.createEjectNoticeDialog(mActivity, this);
                dialog.show();
            } else {
                finish();
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    PictureUtil.deleteDir("compress");
                }catch (Exception e){}
            }
        }).start();

        if (inputMap != null && inputMap.size() > 0) {
            inputMap.clear();
        }
        if (selMap != null && selMap.size() > 0) {
            selMap.clear();
        }
        if (TaocMap != null && TaocMap.size() > 0) {
            TaocMap.clear();
        }
        Tools.dShop = null;
        Tools.sCity = null;
        Tools.sCountry = null;
        Tools.sAction = null;
        Tools.sTaocan = null;
        Tools.sKit = null;
        Tools.sStyle = null;
        Tools.sOneTao = null;
        Tools.sYjazdate = "";
        super.onDestroy();
    }

    //递归上传图片
    private void uploadImages(String spath) {
        File file = new File(spath);
        RequestParams params = new RequestParams();
        params.addBodyParameter("usercode", MyApplication.getUserCode());
        params.addBodyParameter("dir", "image");
        params.addBodyParameter("imgFile", file);
        String url = MyApplication.getApplication().getSERVER_URL()
                + "/javascript/kindeditor/asp.net/appupload_json.ashx";

        HttpUtils httpUtils = new HttpUtils();
        httpUtils.configTimeout(15 * 1000).configSoTimeout(15 * 1000).configRequestRetryCount(3);
        httpUtils.send(HttpRequest.HttpMethod.POST, url, params,
                new RequestCallBack<String>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        showDialog("请稍侯...", true);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        BeanImage bean = gson.fromJson(responseInfo.result, BeanImage.class);
                        if (bean.error == 0) {
                            succeedNum++;
                            String imageP = Tools.ToString(bean.filepath);
                            imagePaths.add(new StringBean(imageP));
                        } else {
                            faileNum++;
                            isUploadeding = false;
                            Toast.show(mActivity, "预订单提交失败,请稍候重试！", Toast.LENGTH_SHORT);
                            dimssDialog();
                        }
                        if (faileNum == 0 && succeedNum < bList.size() - 1) {
                            uploadImages(bList.get(succeedNum).getbPath());
                        }
                        if (succeedNum + faileNum == bList.size() - 1) {
                            succeedNum = 0;
                            faileNum = 0;
                            submitAdvanceOrder();
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        faileNum++;
                        isUploadeding = false;
                        Toast.show(mActivity, "预订单提交失败,请稍候重试！", Toast.LENGTH_SHORT);
                        dimssDialog();
                    }
                });
    }

    private void deleUpLoadPic(String upLoadPath) {
        File file = new File(upLoadPath);
        RequestParams params = new RequestParams();
        params.addBodyParameter("usercode", MyApplication.getUserCode());
        params.addBodyParameter("dir", "image");
        params.addBodyParameter("imgFile", file);
        String url = MyApplication.getApplication().getSERVER_URL()
                + "/Web/common/API/AppHandler.ashx";
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.configTimeout(10 * 1000).configSoTimeout(10 * 1000).configRequestRetryCount(3);
        httpUtils.send(HttpRequest.HttpMethod.POST, url, params,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                    }
                });
    }

    private void deleAllPics() {
        new deleTask().execute(imagePaths);
    }

    class deleTask extends AsyncTask<ArrayList<StringBean>, Integer, Map<Integer, String>> {

        @Override
        protected Map<Integer, String> doInBackground(ArrayList<StringBean>... params) {
            ArrayList<StringBean> imagePs = params[0];
            if (imagePs != null && imagePs.size() > 0) {
                for (int i = 0; i < imagePs.size(); i++) {
                    deleUpLoadPic(imagePs.get(i).getPath());
                }
            }
            return null;
        }
    }


}
